package com.cy.pj.ajax.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    //假设这是数据库的表
    private List<Map<String,Object>> list=new ArrayList<>();
    public AjaxController(){
        Map<String,Object> map=new HashMap<>();
                map.put("id",100);
                map.put("name","华为");
                map.put("remark","Good");
               list.add(map);
    }
    @DeleteMapping("/doAjaxDelete")

    public String doAjaxDelete(String id){
        Iterator<Map<String,Object>> it=list.iterator();
        while(it.hasNext()){
            Map<String,Object> map=it.next();
            if(map.get("id").equals(id)){
                //dbList.remove(map);//这样删除会出现并发删除异常
                it.remove();//通过迭代器执行删除操作
            }
        }
        return "删除成功";
    }
    @PutMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> updateMap){
            Iterator it=list.iterator();
        while(it.hasNext()){
            Map<String,Object> map=(Map<String,Object>)it.next();
            if(map.get("id").equals(updateMap.get("id"))){
                map.put("name",updateMap.get("name"));
                map.put("remark",updateMap.get("remark"));
            }
        }
        return "update ok";
    }



    @PostMapping("/doAjaxPost")

    public String doAjaxPost(@RequestParam Map<String,Object> map){
        list.add(map);
        return"保存成功";
    }
    //@GetMappering 注解描述的方法表示只能处理get请求方式的映射
    @GetMapping("/doAjaxGet")


    public List<Map<String,Object>> doAjaxGet(){
        return list;
    }


    @RequestMapping("/doNotAjaxUI")
    public String doNotAjaxUI(){
        return "not-ajax-01";
    }
    @RequestMapping("/doNotAjaxStart")

    public String doNotAjaxStart(Model model) {
    model.addAttribute("result","do not ajax request result");
        return "not-ajax-01";
    }
@RequestMapping("/doAjaxStart")
@ResponseBody
    public String doAjaxStart() {

        return "第一个";
    }
}
